﻿using Dynamics.NAV.Metro.Common;
using Okra.Data;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dynamics.NAV.Metro.Data
{
    [Export(typeof(INavItemDataSource))]
    [Shared]
    public class NavItemDataSource : INavItemDataSource
    {
        private IList<NavItem> _Items;
        private NavItemDataListSource _dataListSource;
        private NavCompany _currCompany;

        public NavItemDataSource()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                _Items = (IList<NavItem>)new List<NavItem>();
                _Items.Add(new NavItem() { Index = 0, Description = "Desk" });
                _Items.Add(new NavItem() { Index = 1, Description = "Paper" });
                _Items.Add(new NavItem() { Index = 2, Description = "Engine" });
                _Items.Add(new NavItem() { Index = 3, Description = "Samsung TV" });
                _Items.Add(new NavItem() { Index = 4, Description = "Cables" });
            }
        }

        [Import]
        public IDynamicsNavApi NavApi { get; set; }

        public IList<NavItem> GetItems()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
                return _Items;

            if (NavApi == null)
                NavApi = new DynamicsNavApi();

            if (NavApi.CurrentCompany != _currCompany)
            {
                _currCompany = NavApi.CurrentCompany;
                _Items = null;
                _dataListSource = null;
            }

            if (_dataListSource == null)
                _dataListSource = new NavItemDataListSource();

            // Create a single instance of the Item list
            // This can then be shared between multiple view models
            if ((_dataListSource != null) && (_Items == null))
            {
                _Items = (IList<NavItem>)new VirtualizingDataList<NavItem>(_dataListSource);
            }

            return _Items;
        }
    }
}
